package com.uwntek.base.des;

import java.security.MessageDigest;
import java.security.spec.AlgorithmParameterSpec;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class DesSecurity {
    BASE64Encoder encoder;
    BASE64Decoder decoder;
    Cipher enCipher;
    Cipher deCipher;
    /**
     * @param key 加密密钥
     * @param iv 初始化向量
     * @throws Exception
     */
    public DesSecurity(String key, String iv) throws Exception {
        if (key == null) {
            throw new NullPointerException("Parameter is null!");
        }
        initCipher(key.getBytes(), iv.getBytes());
    }
   
    private void initCipher(byte[] secKey, byte[] secIv) throws Exception {
        // 创建MD5散列对象
        MessageDigest md = MessageDigest.getInstance("MD5");
        // 散列密钥
        md.update(secKey);
        // 获得DES密钥
        DESKeySpec   dks   =   new   DESKeySpec(md.digest());
        // 获得DES加密密钥工厂
        SecretKeyFactory   keyFactory   =   SecretKeyFactory.getInstance("DES");
        // 生成加密密钥
        SecretKey   key   =   keyFactory.generateSecret(dks);
        // 创建初始化向量对象
        IvParameterSpec iv = new IvParameterSpec(secIv);
        AlgorithmParameterSpec paramSpec = iv;
        // 为加密算法指定填充方式，创建加密会话对象
        enCipher   =   Cipher.getInstance("DES/CBC/PKCS5Padding");
        // 为加密算法指定填充方式，创建解密会话对象
        deCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        // 初始化加解密会话对象
        enCipher.init(Cipher.ENCRYPT_MODE,   key,   paramSpec); 
        deCipher.init(Cipher.DECRYPT_MODE,   key,   paramSpec);
        encoder = new BASE64Encoder();
        decoder = new BASE64Decoder();
    }
/**
 * 加密数据
     * @param data 待加密二进制数据
     * @return 经BASE64编码过的加密数据
     * @throws Exception
     */
    public String encrypt(byte[] data) throws Exception {
    	
        return encoder.encode(enCipher.doFinal(data));
    }
  public String encrypt(String data) throws Exception {
	    byte[] btstr = data.getBytes("utf-8");
    	
        return encoder.encode(enCipher.doFinal(btstr));
    }
/**
* 解密数据
     * @param data 待解密字符串（经过BASE64编码）
     * @return    解密后的二进制数据
     * @throws Exception
     */
    public byte[] decrypt(String data) throws Exception {  
        return deCipher.doFinal(decoder.decodeBuffer(data));
    }
    public String decryptStr(String data) throws Exception {  
    	byte[] decode= deCipher.doFinal(decoder.decodeBuffer(data));
    	String result =  new String(decode, "GB2312");
        return result;
    }
    public String decryptStrUTF(String data) throws Exception {  
    	byte[] decode= deCipher.doFinal(decoder.decodeBuffer(data));
    	String result =  new String(decode, "utf-8");
        return result;
    }
    
	public static void main(String[] args) throws Exception {
		DesSecurity des = new DesSecurity("UWNTEK_CLIENT", "12345678");
		String msg = "焦化煤气发电";//"焦化煤气发电";
		//String msg="<com.uwntek.entity.XmlBean><project><projectID>12f6004f7ce837</projectID><projectName>热电厂</projectName><url>http://192.168.1.252/web</url><comment>焦化煤气发电控制站</comment><version>v3.0</version></project></com.uwntek.entity.XmlBean>";
		String en =des.encrypt(msg);
	//	byte de[] =des.decrypt(en);
		String de=des.decryptStr(en);
		System.out.println("明文是:" + msg);
		System.out.println("加密后:" + new String(en));
		System.out.println("解密后:" + new String(de));
	}
}
